package com.shj.em.base.support;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
 * @author Shen Huang Jian
 * @since 2018-06-21
 */
@Data
@ApiModel(description = "响应结果")
public class ResMsg<T> implements Serializable {
    private static final long serialVersionUID = 8992436576262574064L;
    @ApiModelProperty("错误消息")
    protected String msg;

    @ApiModelProperty("成功时响应内容")
    protected T result;

    @ApiModelProperty(value = "状态码", required = true)
    protected int status;

    @ApiModelProperty("业务自定义状态码")
    protected String code;


    public ResMsg() {
    }

    public static <T> ResMsg<T> error() {
        return error(500, ResCode.UNKNOWN.getCode(), ResCode.UNKNOWN.getMsg());
    }

    public static <T> ResMsg<T> error(String message) {
        return error(500, ResCode.UNKNOWN.getCode(), message);
    }

    public static <T> ResMsg<T> error(ResCode responseCode) {
        return error(500, responseCode.getCode(), responseCode.getMsg());
    }

    public static <T> ResMsg<T> error(int status, String message) {
        return error(status, ResCode.UNKNOWN.getCode(), message);
    }

    public static <T> ResMsg<T> error(int status, String code, String message) {
        ResMsg<T> msg = new ResMsg();
        msg.msg = message;
        msg.status(status);
        msg.code(code);
        return msg;
    }


    public static <T> ResMsg<T> ok() {
        return ok(ResCode.SUCCESS.getMsg(),null);
    }

    public static <T> ResMsg<T> ok(T result) {
        return ok(ResCode.SUCCESS.getMsg(),result);
    }

    public static <T> ResMsg<T> ok(String msg, T result) {
        ResMsg resMsg = new ResMsg();
        return resMsg.result(result).code(ResCode.SUCCESS.getCode()).status(200).msg(msg);
    }

    public ResMsg<T> result(T result) {
        this.result = result;
        return this;
    }

    public String toString() {
        return JSON.toJSONStringWithDateFormat(this, "yyyy-MM-dd HH:mm:ss", new SerializerFeature[0]);
    }

    public ResMsg<T> status(int status) {
        this.status = status;
        return this;
    }

    public ResMsg<T> code(String code) {
        this.code = code;
        return this;
    }

    public ResMsg<T> msg(String msg) {
        this.msg = msg;
        return this;
    }

}

